<?php

/**
 * Created by PhpStorm.
 * User: apple
 * Date: 2019/11/28
 * Time: 2:02 PM
 */
namespace app\index\controller;

use app\admin\model\halt\Cate;
use app\admin\model\Houseout;
use app\admin\model\Stock;
use app\admin\model\Supplier;
use think\Db;

class Retpur extends Store
{
    public $userArr=["1","ZhangWei","ZhanZhiWei"];//"ZhanZhiWei|1|ZhangWei";
    public $followId=4;
    public $statusArr=[9,8];
    public function _initialize()
    {
        parent::_initialize();
    }
    public function index(){

        $sql='';
        $end="";
        //检测审核权限
        $userid = $this->user['userid'];
        $status = $this->request->post("status");
        $title = $this->request->post("title");
        $supplier= $this->request->post("supplier");
        if (!empty($title)){
            $end.=" and order_id like '%{$title}%'";
        }
        if (!empty($supplier)){
            $end.=" and supplier={$supplier}";
        }
        $tempArr=[];
        foreach ($this->statusArr as $v){
            $work=$this->workflow($this->followId,$v);
            $temp = explode(",",$work['auto_sponsor_ids']);
            if (in_array($userid,$temp)){
                $tempArr[]=$v;
            }
        }
        if (!in_array($this->user['userid'], $this->userArr)){
            if ($tempArr){
                $workData = $this->getWork();
                $strSta=implode(",",$tempArr);

                if (!empty($workData)){
                    $sql="id in({$workData}) or status in({$strSta})";
                }else{
                    $sql="status in({$strSta})";
                }
            }else{
                return '';
            }
        }else{
            //如果有审核权限
            if ($tempArr){
                $workData = $this->getWork();
                $strSta=implode(",",$tempArr);
                if ($status!='' && $status==9){
                    $sql.="(publisher='{$userid}' and status in(9,8,7))  or status in({$strSta}) {$end}";
                }else{
                    if ($status==null){
                        if ($workData!=''){
                            $sql.="(publisher='{$userid}' or id in({$workData}) or status in({$strSta})) {$end}";
                        }else{
                            $sql.="(publisher='{$userid}'  or status in({$strSta})) {$end}";

                        }


                    }else{
                        $sql.="publisher='{$userid}' and status={$status} {$end}";

                    }
                }


            }else{
                if ($status){
                    if ($status==9){
                        $sql.="publisher='{$userid}' and status in(9,8) {$end}";

                    }else{
                        $sql.="publisher='{$userid}' and status={$status} {$end}";

                    }
                }else{
                    $sql.="publisher='{$userid}' {$end}";
                }
            }
        }

        if ($this->request->isAjax())
        {

            $page = isset($_POST['counter']) ? intval($_POST['counter']) : 1;
            $offset = 4*($page-1);
            $info = Db::name("purret")->where($sql)->limit($offset,4)->order("id desc")->select();

            foreach ($info as $k=>$v){
                $info[$k]['supplier']=$this->getSup($v['supplier']);
                $info[$k]['createtime']=date("Y-m-d");
                $info[$k]['publisher']=$this->getPublisher($v['publisher']);
                $info[$k]['status']=$this->getStatus($v['status']);
            }
            $result = array("list"=>$info);
            return json($result);
        }
        $list = Db::name('supplier')->field("id,sname")->select();
        $this->view->assign("list", $list);

        $this->view->assign("userid", $this->user['userid']);
        $this->view->assign("userarr", $this->userArr);

        return $this->view->fetch();

    }
    public function view($id)
    {

        $info = Db::name('purret')->where(array('id' => $id))->find();
        //检测是否是自己发布
        if ($info['publisher']!=$this->user['userid']){
            $bool=false;
            foreach ($this->statusArr as $v){
                $work=$this->workflow($this->followId,$v);
                $temp = explode(",",$work['auto_sponsor_ids']);
                if (in_array($this->user['userid'],$temp)){
                    $bool=true;
                }
            }
            if (!$bool)$this->error("没有权限");
        }
        $info['supplier'] = $this->getSup($info['supplier']);
        $info['status_text'] = $this->getStatus($info['status']);
        $info['username'] = $this->getPublisher($info['publisher']);
        $info['count'] = Db::name('purret_data')->where(array('pur_id' => $id))->count();
        $list = Db::name('purret_data')->field("shopid,num,price")->where(array('pur_id' => $id))->select();
        $listarr = [];
        foreach ($list as $k => $v) {
            $listarr["flg_".$v['shopid']]=$v;
            $listarr["flg_".$v['shopid']]['cname'] = $this->getCname($v['shopid']);
            $listarr["flg_".$v['shopid']]['total'] = $v['num'];
            $listarr["flg_".$v['shopid']]['storenum'] = $this->getStore($v['shopid']);;

        }
        //审批通过流程
        $worklist = Db::name("purret_work")->where(array("pid" => $id))->select();

        if ($worklist) {
            foreach ($worklist as $k => $v) {
                $worklist[$k]['user'] = $this->getInfo($v['publisher']);
            }
        }
        if($pos = array_search($info['status'],$this->statusArr)!==false){
            $work = $this->workflow($this->followId,$info['status']);
            $userList = explode(",",$work['auto_sponsor_ids']);
            if ($userList){
                foreach ($userList as $k=>$v){
                    $array=[
                        'status'=>3,
                        "user"=>$this->getInfo($v),
                        'mark'=>''
                    ];
                    array_push($worklist,$array);

                }
            }

        }
        $this->view->assign('worklist',$worklist);
        $this->view->assign('jsList',json_encode($listarr));
        $this->view->assign('list',$listarr);
        $this->view->assign('info',$info);
        $this->view->assign('userid',$this->user['userid']);

        //权限处理
        $userArr=array();
        switch ($info['status']){
            case 9:
                $work2 = $this->workflow($this->followId,9);
                $userArr = explode(",",$work2['auto_sponsor_ids']);
                break;
            case 8:
                $work2 = $this->workflow($this->followId,8);
                $userArr = explode(",",$work2['auto_sponsor_ids']);
                break;
            default:
                $userArr = explode(",",$info['publisher']);;
                break;
        }
        $purinfo=null;

        if ($info['cid'] > 0){

            $purinfo = Db::name("purcha")->where(array("id"=>$info['cid']))->field("order_id")->find();
            $this->view->assign('purinfo',$purinfo['order_id']);

        }

        $this->view->assign('userArr',$userArr);

        return $this->view->fetch();
    }
    public function edit($id){
        $info = Db::name('purret')->where(array('id'=>$id))->find();

        if ($info['publisher']!=$this->user['userid'])$this->error("您没有权限");
        if ($info['status']==10 || $info['status']==5){
            if ($this->request->isAjax() && $this->request->isPost()){
                $post = $_POST;
                $post['createtime']=strtotime($post['riqi']);
                $shopList = $post['shopList'];
                unset($post['riqi'],$post['order_id'],$post['shopList'],$post['sub']);
                Db::name("purret")->where(array("id"=>$id))->update($post);
                Db::name('purret_data')->where(array("pur_id"=>$id))->delete();
                foreach ($shopList as $k=>$v){
                    Db::name('purret_data')->insert(array('shopid'=>$v['id'],'num'=>$v['num'],'price'=>isset($v['price']) ? $v['price'] : 0,'pur_id'=>$id));
                }
                if ($post['status']==9){
                    $work = $this->workflow($this->followId,9);
                    $person = str_replace(",","|",$work['auto_sponsor_ids']);

                    $this->sendText("待审核通知","<div class=\"gray\">退货单\n审核状态：待1级审核</div>",$this->host."index/retpur/view/id/".$pid,$person);

                }
                $this->setWork($info,$post['status']);

                $this->success("编辑成功","/index/retpur/view/id/".$id);
            }


            $preCate = Db::name("halt_cate")->field('id,pid,name')->where(array("type"=>1,"pid"=>0))->order("id asc")->select();
            $firstCate=$preCate[0]['id'];
            $cate = Db::name("halt_cate")->field('id,pid,name')->where(array("pid"=>$firstCate))->order("id asc")->select();
            foreach ($cate as $k=>$v){
                $cate[$k]['cateArr']=Db::name("halt_cate")->field('id,pid,name')->where(array("pid"=>$v['id']))->order("id asc")->select();
            }
            $this->view->assign("preCate", $preCate);
            $this->view->assign("cate", $cate);
            /*供应商*/
            $sdb = new Supplier();
            $supInfo = collection($sdb->select())->toArray();

            $sup = $sdb->where(array("id"=>$info['supplier']))->find();
            $info['porder_id']='';

            if ($info['cid'] > 0){
                $pinfo = Db::name("purcha")->where(array("id"=>$info['cid']))->field("order_id")->find();
                $info['porder_id']=$pinfo['order_id'];
            }

            $this->view->assign("supInfo", $supInfo);
            $this->view->assign("sup", $sup);
            $this->view->assign("username", $this->user['username']);

            $purList=Db::name('purret_data')->field('shopid as id,num,price')->where(array("pur_id"=>$id))->select();
            foreach ($purList as $k=>$v){
                $purList[$k]['number']=$v['num'];
                $purList[$k]['cname']=$this->getCname($v['id']);
                $purList[$k]['storenum']=$this->getStore($v['id']);
                if ($info['cid'] > 0){
                    $data = Db::name("purcha_data")->field("actual")->where(array("pur_id"=>$info['cid'],"shopid"=>$v['id']))->find();
                    $purList[$k]['actual']=$data['actual'];

                }
            }
            $this->view->assign("info",$info);
            $this->view->assign("purList", json_encode($purList));

            return $this->view->fetch();
        }else{
            $this->error("当前采购单不能编辑","/index/store/view/id/".$id);
        }
    }
    function reject2(){
        $id = $this->request->post("id");
        $status = $this->request->post("status");
        $mark = $this->request->post("mark");
        if (!$id || $status=='')$this->error("参数错误");
        if ($mark=='')$this->error("请提交驳回意见");
        if (!in_array($status,$this->statusArr))$this->error("操作失败");
        if (in_array($status,array(4,1)))$this->error("此订单不能操作");
        $post = array_search($status, $this->statusArr);
        $work = $this->workflow($this->followId,$status);//查询当前是否是对应的用户名

        $user = $this->user;
        $userList = explode(",",$work['auto_sponsor_ids']);
        $userid = $user['userid'];
        if (!in_array($userid,$userList))$this->error("没有权限");
        DB::name("purret")->where(array("id"=>$id))->update(array("status"=>5));
        DB::name("purret_work")->insert(array(
            "pid"=>$id,
            "inputtime"=>time(),
            "publisher"=>$userid,
            "mark"=>$mark,
            "status"=>2
        ));
        $info = Db::name('purret')->where(array('id'=>$id))->find();
        $this->setWork($info,5);
        $this->sendText("驳回通知","订单号：{$info['order_id']}被驳回。\n原因：".$mark,$this->host."index/retpur/view/id/".$id,$info['publisher']);

        /*
         * 驳回通知
         * */
        $this->success("操作成功");



    }


    public function oper(){
        $id = $this->request->post("id");
        $status = $this->request->post("status");
        if (!$id || $status=='')$this->error("参数错误");
        if (isset($_POST['mark']) && $_POST['mark']){
            $mark = trim($_POST['mark']);
        }

        $userid = $this->user['userid'];
        $info = Db::name('purret')->where(array('id'=>$id))->find();
        if (in_array($status,array(4,1)))$this->error("此订单不能操作");
        if (in_array($status,$this->statusArr)){
            //检查审核权限
            $check = $this->workflow($this->followId,$status);

            $userArr = explode(",",$check['auto_sponsor_ids']);

            if (!in_array($userid,$userArr)){
                $this->error("您没有权限");
            }
        }


        switch ($status){
            case 10:
                if ($info['publisher']!=$userid)$this->error("您没有权限");
                //检查权限
                Db::name("purret")->where(array("id"=>$id))->update(array("status"=>9));

                $work = $this->workflow($this->followId,9);
                $userList = str_replace(",","|",$work['auto_sponsor_ids']);

                $this->sendText("待审核通知","<div class=\"gray\">退货单\n审核状态：待1级审核</div>",$this->host."index/retpur/view/id/".$info['id'],$userList);

                $this->setWork($info,9);
                $this->success("操作成功");
                break;
            case 9:

                $this->shenhe2($id,$status,$info);
            case 8:
                Db::name("purret")->where(array("id"=>$id))->update(array("status"=>1));
                $this->setWork($info,1);
                pushMsgText($this->config,"text",array("content"=>"您的订单已经通过审核".$info['order_id']),$info['publisher']);
                $purList=Db::name('purret_data')->field('shopid,num')->where(array("pur_id"=>$id))->select();
                //减库存
                $hDb = new Houseout();
                $stDb = new Stock();
                $orderId=$hDb->getOrderId();
                foreach ($purList as $v){
                    $arr = array(
                        "order_id"=>$orderId,
                        "type"=>1,
                        "shopid"=>$v['shopid'],
                        "num"=>$v['num'],
                        "cid"=>1,
                        "inputtime"=>time(),
                        "pur_id"=>$id,
                        "publisher"=>$userid,
                        "mark"=>"采购退货"
                    );
                    $stDb->where(array("cid"=>1,"shopid"=>$v["shopid"]))->setDec("num",$v['num']);
                    $hDb->insert($arr);
                }
                $this->success("操作成功");

                break;

            case 5:
                Db::name("purret")->where(array('id'=>$id))->update(array("status"=>4));
                $this->setWork($info,4);
                $this->success("操作成功");
                break;

        }
    }
    //审核通知
    protected function shenhe2($id,$status,$info){

        $status =  $status==8 ? 1 : $status-1;

        $userid=$this->user['userid'];
        Db::name("purret")->where(array("id"=>$id))->update(array("status"=>$status));
        Db::name("purret_work")->insert(array(
            "pid"=>$id,
            "inputtime"=>time(),
            "publisher"=>$userid,
            "mark"=>'',
            "status"=>1
        ));
        $this->setWork($info,$status);
        if ($status==1){
            $this->sendText("审核成功通知","<div class=\"gray\">单号：{$info['order_id']}已经通过审核",$this->host."index/retpur/view/id/".$info['id'],$info['publisher']);
        }else{
            $work = $this->workflow($this->followId,$status);
            $userList = str_replace(",","|",$work['auto_sponsor_ids']);
            $this->sendText("待审核通知","<div class=\"gray\">退货单\n审核状态：待{$work['step']}级审核</div>",$this->host."index/retpur/view/id/".$info['id'],$userList);

        }



        $this->success("操作成功");
    }
    protected function workflow($id,$status){
        $list = DB::name("flow_process")->field("auto_sponsor_ids,range_user_ids")->where(array("flow_id"=>$id))->select();
        $array=array(
            "8"=>1,
            "9"=>0
        );

        if (!isset($array[$status])) return false;

        if($list[$array[$status]]['auto_sponsor_ids']==''){
            $list[$array[$status]]['auto_sponsor_ids']=$list[$array[$status]]['range_user_ids'];
        }

        return array_merge(array("step"=>$array[$status]+1), $list[$array[$status]]);


    }
    //操作流程
    protected function setWork($info,$status){
        $id = $info["id"];
        if ($work = Db::name("workflow")->field("id")->where(array("tid"=>$id,"type"=>2))->find()){
            Db::name("workflow")->where(array("id"=>$work['id']))->update(array("status"=>$status,"uptime"=>time()));
        }else{
            Db::name("workflow")->insert(array("tid"=>$id,"status"=>$status,"order_id"=>$info['order_id'],"type"=>2,"inputtime"=>$info['createtime'],"uptime"=>time(), "userid"=>$this->user['userid']));

        }
        return true;

    }
    public function add()
    {

        if (!in_array($this->user['userid'], $this->userArr)) $this->error("您没有权限", "/index/store/lists");
        if ($this->request->isPost() && isset($_POST['sub'])) {
            $post = $_POST;
            $post['createtime']=strtotime($post['riqi']);
            $post['publisher']=$this->user['userid'];
            $shopList = $post['shopList'];
            $post['order_id']=$this->getOrderId();
            unset($post['riqi'],$post['shopList'],$post['sub']);
            $pid = Db::name("purret")->insert($post,0,1);
            if (!$pid) {
                Db::rollback();
                $this->error("订单号重复");
            }
            foreach ($shopList as $k=>$v){
                $check=Db::name('purret_data')->insert(array('shopid'=>$v['id'],'num'=>$v['num'],'price'=>isset($v['price']) ? $v['price'] : 0,'pur_id'=>$pid));
                if (!$check)break;
            }
            if (!$check){
                Db::rollback();
                $this->error("添加失败");
            }else{

               //这里写推送消息
                if ($post['status']==9){
                    $work = $this->workflow($this->followId,9);
                    $person = str_replace(",","|",$work['auto_sponsor_ids']);

                    $this->sendText("待审核通知","<div class=\"gray\">退货单\n审核状态：待1级审核</div>",$this->host."index/retpur/view/id/".$pid,$person);


                }
                $this->setWork(Db::name("purret")->where(array("id"=>$pid))->find(),$post['status']);
                $this->success("添加成功");
            }
        }
        $order_id = $this->getOrderId();
        $this->view->assign("order_id", $order_id);
        $this->view->assign("username", $this->user['username']);
        $preCate = Db::name("halt_cate")->field('id,pid,name')->where(array("type"=>1,"pid"=>0))->order("id asc")->select();
        $firstCate=$preCate[0]['id'];
        $cate = Db::name("halt_cate")->field('id,pid,name')->where(array("pid"=>$firstCate))->order("id asc")->select();
        foreach ($cate as $k=>$v){
            $cate[$k]['cateArr']=Db::name("halt_cate")->field('id,pid,name')->where(array("pid"=>$v['id']))->order("id asc")->select();
        }

        $this->view->assign("preCate", $preCate);
        $this->view->assign("cate", $cate);
        $sdb = new Supplier();
        $supInfo = collection($sdb->order('id desc')->select())->toArray();
        $sup = reset($supInfo);
        $this->view->assign("sup", $sup);

        $this->view->assign("supInfo", $supInfo);
        return $this->view->fetch();
    }
    protected function getOrderId(){
        $order_id = "CGTH" . date('Ymd') . substr(time(),6,4).random(4, 1);
        $info =Db::name("purret")->where(array('order_id' => $order_id))->find();
        if ($info) {
            $this->getOrderId();
        } else {
            return $order_id;
        }
    }
    public function getCgList(){
        $page = isset($_POST['page']) ? intval($_POST['page']) : 1;
        $sup = $this->request->post("sup");

        $offset = 4*($page-1);
        $info = Db::name("purcha")->where(array("status"=>1,"supplier"=>$sup))->limit($offset,4)->order("id desc")->select();
        foreach ($info as $k=>$v){
            $info[$k]['supplier']=$this->getSup($v['supplier']);
            $info[$k]['createtime']=date("Y-m-d");
            $info[$k]['publisher']=$this->getPublisher($v['publisher']);
        }
        return json(array("list"=>$info));
    }
    //获取当前订单的入库数据
    public function getPurData(){
        $id = $this->request->post("id");
        if($id==null)$this->error("加载错误");
        $info = Db::name("purcha_data")->where(array("pur_id"=>$id))->select();
        if ($info){
            foreach ($info as $k=>$v){
                $info[$k]['cname']=$this->getCname($v['shopid']);
                $info[$k]['number']=$v['actual'];
                $info[$k]['id']=$v['shopid'];
                $info[$k]['storenum']=$this->getStore($v['shopid']);
            }
        }
        return json(array("list"=>$info));
    }
}